package com.cn.onetrip.activity;

import java.util.ArrayList;
import java.util.List;

import com.cn.onetrip.objects.AtlasObj.PictureObj;
import com.cn.onetrip.rorate3d.AtlasGallery;
import com.cn.onetrip.rorate3d.ScenicGalleryAdapter;
import com.cn.onetrip.activity.R;
import com.cn.onetrip.untility.SBCToDBC;
import com.cn.onetrip.untility.SysApplication;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ScenicAtlasActivity extends Activity {
	private AtlasGallery gallery;
	private ScenicGalleryAdapter adapter;
	// private AtlasObj atlasObj;

	private TextView textTitle;
	private TextView textViewDesc, textViewPage;
	public RelativeLayout layout;
	public Button returnButton;
	public boolean showText = true;
	private int num = 0;
	List<String> url = new ArrayList<String>();

	private String texts[], imageUrl[];
	private List<String> loadImageUrl;
	RelativeLayout layoutTitle;
	private int count = 0;
	private ProgressBar pb;
	private int loadImageCount;
	public final int loadImageSize = 5;
	public boolean isLastLoad = false;
	private int pageNum = 0;
	int visibCount = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		if (SysApplication.slidesList.size() == 0) {
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
		setContentView(R.layout.activity_scenic_atlas);
		// atlasObj = (AtlasObj) getIntent().getParcelableExtra("atlas");

		layoutTitle = (RelativeLayout) findViewById(R.id.layout_title);
		layout = (RelativeLayout) findViewById(R.id.Atlas_RelativeLayout);
		textTitle = (TextView) findViewById(R.id.text_title);
		textViewDesc = (TextView) findViewById(R.id.textview_desc);
		textViewPage = (TextView) findViewById(R.id.atlas_textview_page);
		pb = (ProgressBar) findViewById(R.id.atlas_pb);

		loadImageUrl = new ArrayList<String>();
		List<PictureObj> slidesList = SysApplication.slidesList;
		texts = new String[slidesList.size()];
		imageUrl = new String[slidesList.size()];
		for (int i = 0; i < slidesList.size(); i++) {
			PictureObj pictureObj = slidesList.get(i);
			texts[i] = pictureObj.imageDescription;
			imageUrl[i] = pictureObj.imageUrl;
		}
		adapter = new ScenicGalleryAdapter(ScenicAtlasActivity.this, mHandler,
				imageUrl, texts);

		setGallery((AtlasGallery) findViewById(R.id.gallery));
		getGallery().setVerticalFadingEdgeEnabled(false);
		getGallery().setHorizontalFadingEdgeEnabled(false);
		getGallery().setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				pageNum = arg2 % imageUrl.length;
				if (ScenicGalleryAdapter.imagesCache.size() != imageUrl.length
						&& !ScenicGalleryAdapter.imagesCache
								.containsKey(imageUrl[pageNum])) {
					GalleryWhetherStop();
				}

				// if (ScenicGalleryAdapter.imagesCache.size() !=
				// imageUrl.length
				// && arg2 / loadImageSize == loadImageCount + 1) {
				// loadImageCount++;
				// GalleryWhetherStop();
				// }
				num = arg2;
				Message msg = Message.obtain();
				msg.what = 2;
				mHandler.sendMessage(msg);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		returnButton = (Button) findViewById(R.id.quit);
		returnButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				System.gc();
				overridePendingTransition(R.anim.push_left_translate,
						R.anim.pull_right_translate);
			}
		});
		GalleryWhetherStop();

	}

	/**
	 */
	private void GalleryWhetherStop() {
		Runnable runnable = new Runnable() {
			public void run() {
				try {
					// int index = 0;
					// index = num;
					// Thread.sleep(1000);
					// if (index == num) {
					// url.add(atlasObj.picList.get(num
					// % atlasObj.picList.size()).imageUrl);
					// if (num != 0 && num % atlasObj.picList.size() - 1 >= 0) {
					// url.add(atlasObj.picList.get(num
					// % atlasObj.picList.size() - 1).imageUrl);
					// }
					// if (num != atlasObj.picList.size() - 1
					// && num % atlasObj.picList.size() + 1 != atlasObj.picList
					// .size()) {
					// url.add(atlasObj.picList.get(num
					// % atlasObj.picList.size() + 1).imageUrl);
					// }
					// if (num == 0 || num % atlasObj.picList.size() - 1 < 0) {
					// url.add(atlasObj.picList.get(atlasObj.picList
					// .size() - 1).imageUrl);
					// }
					// if (num == atlasObj.picList.size() - 1
					// || num % atlasObj.picList.size() + 1 == atlasObj.picList
					// .size()) {
					// url.add(atlasObj.picList.get((num + 1)
					// % atlasObj.picList.size()).imageUrl);
					// }
					Message m = new Message();
					m.what = 1;
					mHandler.sendMessage(m);
					// }
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}

	class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			try {
				String url = params[0];
				ScenicGalleryAdapter.loadImageFromUrl(url);

				// count++;
				// if (!isLastLoad) {
				// if (count == loadImageSize) {
				// count = 0;
				// Thread.sleep(500);
				// Message m = new Message();
				// m.what = 0;
				// mHandler.sendMessage(m);
				// }
				// } else {
				// if (count == imageUrl.length - loadImageCount
				// * loadImageSize) {
				// count = 0;
				// Thread.sleep(500);
				// Message m = new Message();
				// m.what = 0;
				// mHandler.sendMessage(m);
				// }
				// }

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// count++;
				// if (count == loadImageUrl.size()) {
				visibCount--;
				if (visibCount == 0) {
					// count = 0;
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					Message m = new Message();
					m.what = 0;
					mHandler.sendMessage(m);
				}
			}
			return bitmap;
		}
	}

	private boolean isFirstLoad = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case 0: {
					if (!isFirstLoad) {
						getGallery().setAdapter(adapter);
						getGallery().setSelection(
								Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2
										% imageUrl.length);
					}
					isFirstLoad = true;
					pb.setVisibility(View.GONE);
					adapter.notifyDataSetChanged();
					break;
				}
				case 1: {
					// pb.setVisibility(View.VISIBLE);
					// if (imageUrl.length <= loadImageSize * (1 +
					// loadImageCount)) {
					// isLastLoad = true;
					// for (int i = loadImageCount * loadImageSize; i <
					// imageUrl.length; i++) {
					// LoadImageTask task = new LoadImageTask();
					// task.execute(imageUrl[i]);
					// }
					// } else {
					// for (int i = loadImageCount * loadImageSize; i <
					// loadImageSize
					// * (1 + loadImageCount); i++) {
					// LoadImageTask task = new LoadImageTask();
					// task.execute(imageUrl[i]);
					// }
					// }

					pb.setVisibility(View.VISIBLE);
					if (pageNum == 0) {
						loadImageUrl.add(imageUrl[imageUrl.length - 1]);
						loadImageUrl.add(imageUrl[pageNum]);
						loadImageUrl.add(imageUrl[pageNum + 1]);
					} else if (pageNum == imageUrl.length - 1) {
						loadImageUrl.add(imageUrl[imageUrl.length - 2]);
						loadImageUrl.add(imageUrl[imageUrl.length - 1]);
						loadImageUrl.add(imageUrl[0]);
					} else {
						loadImageUrl.add(imageUrl[pageNum - 1]);
						loadImageUrl.add(imageUrl[pageNum]);
						loadImageUrl.add(imageUrl[pageNum + 1]);
					}
					for (int i = 0; i < loadImageUrl.size(); i++) {
						LoadImageTask task = new LoadImageTask();
						task.execute(loadImageUrl.get(i));
						visibCount++;
					}
					loadImageUrl.clear();
				}
				case 2: {
					if (isFirstLoad) {
						setTextViewContent();
					}
				}
				}
				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	public void setTextViewState() {
		if (showText) {
			layoutTitle.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.pull_top_translate));
			layout.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.pull_bottom_translate));
			layoutTitle.setVisibility(View.INVISIBLE);
			layout.setVisibility(View.INVISIBLE);
			showText = false;
		} else {
			layoutTitle.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_top_translate));
			layout.setAnimation(AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.push_bottom_translate));
			layoutTitle.setVisibility(View.VISIBLE);
			layout.setVisibility(View.VISIBLE);
			showText = true;
		}
	}

	public void setTextViewContent() {
		String description = texts[num % texts.length];
		textViewDesc.setText(SBCToDBC.ToDBC(description));
		textViewDesc.setAnimation(AnimationUtils.loadAnimation(
				getApplicationContext(), R.anim.push_bottom_translate));
		textViewPage.setText((num % imageUrl.length + 1) + "/"
				+ imageUrl.length);

		// layout.setAnimation(AnimationUtils.loadAnimation(
		// getApplicationContext(), R.anim.push_bottom_translate));

	}

	public AtlasGallery getGallery() {
		return gallery;
	}

	public void setGallery(AtlasGallery gallery) {
		this.gallery = gallery;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_left_translate,
					R.anim.pull_right_translate);
			System.gc();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		ScenicGalleryAdapter.imagesCache.clear();
		super.onDestroy();
	}

}
